
import { getSeriesImages } from "@/api/pacs/dicom";

// 创建DICOM数据服务
export class DicomDataService {
    constructor() {
        // 七牛云配置常量（与后端保持一致）
        this.qiniuConfig = {
            bucket: 'zang-dicm',
            domain: 'http://dicom.jiannong.vip'
        };
    }

    /**
     * 创建图像ID列表 - 直接使用OSS链接
     */
    async createImageIds(studyId, seriesInstanceUid) {
        try {
            // 1. 调用后端API获取序列图像数据
            const response = await getSeriesImages(studyId, seriesInstanceUid);

            if (!response) {
                throw new Error('后端返回空响应');
            }

            // 2. 从响应中提取images数组和七牛云配置
            const { images, qiniuConfig } = response.data;

            if (!images || !Array.isArray(images)) {
                throw new Error('后端返回的images字段无效或不是数组');
            }

            // 3. 更新七牛云配置（如果后端返回了配置）
            if (qiniuConfig) {
                this.setQiniuConfig(qiniuConfig);
            }

            // 4. 直接使用OSS链接构建imageIds（跟随页面协议）
            const pageIsHttps = typeof window !== 'undefined' && window.location && window.location.protocol === 'https:';
            const imageIds = images.map((ossUrl) => {
                let finalUrl = (ossUrl || '').trim();
                if (!/^https?:\/\//i.test(finalUrl)) {
                    finalUrl = `${pageIsHttps ? 'https' : 'http'}://${finalUrl}`;
                }
                return `qiniu:${finalUrl}`;
            });

            // 5. 返回包含imageIds和其他信息的对象
            return {
                imageIds,
                images,
                count: images.length,
                qiniuConfig: this.qiniuConfig
            };

        } catch (error) {
            console.error('创建图像ID列表失败:', error);
            throw new Error(`创建图像ID列表失败: ${error.message}`);
        }
    }


    /***
     * 从七牛云获取图像数据，为了方便 使用Fetch
     */
    async fetchDicomDataFromQiniu(ossUrl){
        try {
            // 清理和标准化URL格式：优先页面协议，必要时在 https 页面回退到 http
            const pageIsHttps = typeof window !== 'undefined' && window.location && window.location.protocol === 'https:';
            let finalUrl = (ossUrl || '').trim();

            if (!/^https?:\/\//i.test(finalUrl)) {
                finalUrl = `${pageIsHttps ? 'https' : 'http'}://${finalUrl}`;
            }

            const tryFetch = async (url) => fetch(url, {
                method: 'GET',
                headers: { 'Accept': 'application/dicom, */*' }
            });

            let response = await tryFetch(finalUrl);
            if (!response.ok && pageIsHttps && finalUrl.startsWith('https://')) {
                const httpUrl = finalUrl.replace(/^https:\/\//i, 'http://');
                response = await tryFetch(httpUrl);
            }

            if (!response.ok) {
                const errorText = await response.text().catch(() => '');
                throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
            }

            return await response.arrayBuffer();
        } catch (error) {
            console.error('从七牛云获取DICOM文件失败:', error);
            throw error;
        }
    }

    /**
     * 从七牛云获取DICOM文件
     */
    async fetchDicomFromQiniu(ossUrl) {
        try {
            const pageIsHttps = typeof window !== 'undefined' && window.location && window.location.protocol === 'https:';
            let finalUrl = (ossUrl || '').trim();

            if (!/^https?:\/\//i.test(finalUrl)) {
                finalUrl = `${pageIsHttps ? 'https' : 'http'}://${finalUrl}`;
            }

            const tryFetch = async (url) => fetch(url, {
                method: 'GET',
                headers: { 'Accept': 'application/dicom, */*' }
            });

            let response = await tryFetch(finalUrl);
            if (!response.ok && pageIsHttps && finalUrl.startsWith('https://')) {
                const httpUrl = finalUrl.replace(/^https:\/\//i, 'http://');
                response = await tryFetch(httpUrl);
            }

            if (!response.ok) {
                const errorText = await response.text().catch(() => '');
                throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
            }

            return await response.arrayBuffer();
        } catch (error) {
            console.error('从七牛云获取DICOM文件失败:', error);
            throw error;
        }
    }

    /**
     * 验证DICOM文件格式
     */
    validateDicomFile(arrayBuffer) {
        try {
            const uint8Array = new Uint8Array(arrayBuffer);

            // 检查文件大小
            if (uint8Array.length < 132) {
                console.error('文件太小，不是有效的DICOM文件');
                return false;
            }

            // 检查DICOM前缀（从128字节开始应该是"DICM"）
            const prefix = String.fromCharCode(...uint8Array.slice(128, 132));

            if (prefix !== 'DICM') {
                console.warn('文件可能不是标准的DICOM格式，缺少DICM前缀');
            }

            return true;
        } catch (error) {
            console.error('DICOM文件验证失败:', error);
            return false;
        }
    }

    /**
     * 设置七牛云配置
     */
    setQiniuConfig(config) {
        if (config) {
            this.qiniuConfig = { ...this.qiniuConfig, ...config };
        }
    }

    /**
     * 验证七牛云配置
     */
    validateQiniuConfig() {
        const requiredFields = ['bucket', 'domain'];
        const missing = requiredFields.filter(field => !this.qiniuConfig[field]);

        if (missing.length > 0) {
            throw new Error(`七牛云配置缺少必要字段: ${missing.join(', ')}`);
        }

        return true;
    }

    //文件格式检查
    validateFileFormat(arrayBuffer) {
        try {
            const uint8Array = new Uint8Array(arrayBuffer);

            // 检查文件大小
            if (uint8Array.length < 132) {
                return { isValid: false, reason: '文件太小' };
            }

            // 检查DICOM前缀
            const prefix = String.fromCharCode(...uint8Array.slice(128, 132));
            if (prefix === 'DICM') {
                return { isValid: true, format: 'DICOM' };
            }

            // 检查其他可能的格式
            // 检查JPEG
            if (uint8Array[0] === 0xFF && uint8Array[1] === 0xD8) {
                return { isValid: true, format: 'JPEG' };
            }

            // 检查PNG
            if (uint8Array[0] === 0x89 && uint8Array[1] === 0x50 &&
                uint8Array[2] === 0x4E && uint8Array[3] === 0x47) {
                return { isValid: true, format: 'PNG' };
            }

            return { isValid: false, reason: '未知文件格式' };

        } catch (error) {
            return { isValid: false, reason: error.message };
        }
    }
}

// 创建默认实例
const dicomService = new DicomDataService();
export default dicomService;